package cn.wangkai.peanut.mvc.admin.dao.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.wangkai.peanut.cache.Cache;
import cn.wangkai.peanut.cache.WebCacheManager;
import cn.wangkai.peanut.db.DbFactory;
import cn.wangkai.peanut.db.iface.IDbFactory;
import cn.wangkai.peanut.db.iface.IMyDb;
import cn.wangkai.peanut.db.manager.ManagerImp;
import cn.wangkai.peanut.mvc.admin.model.MenuRight;
import cn.wangkai.peanut.mvc.admin.model.Navmenu;
import cn.wangkai.peanut.mvc.admin.model.Right;



public class MenurightManagerImp extends ManagerImp<MenuRight> implements MenurightManager {
	
	private static final Log log = LogFactory.getLog(MenurightManagerImp.class);
	private NavmenuManager navmenuManager = new NavmenuManagerImp();
	public IDbFactory dbFactory = new DbFactory();

	private static Cache cache;
	public void destroy(){
		WebCacheManager.stop();
	}
	public Class<?> getModuleClass(){
		return MenuRight.class;
	}
	public MenurightManagerImp() {
		log.debug("bein menuright");
		if(cache==null)	cache = WebCacheManager.getCache("menu", true);
	}

	public List<Right> findAll(IMyDb db,String menuid) throws Exception{
		String SQL = "SELECT b.* FROM tb_sus_menuright a ";
		SQL += "LEFT JOIN tb_sus_right b on b.RIGHTID=a.RIGHTID WHERE 1=1 AND a.MENUID=? order by a.sid";
		return dbFactory.query(db, SQL.toString(), Right.class,menuid);
	}
	
	public MenuRight findById(IMyDb db,String sid)  throws Exception {
		MenuRight menuright = null;
		String queryString = "SELECT * from tb_sus_menuright where sid= ?";
		menuright = (MenuRight) dbFactory.getOne(db, queryString,MenuRight.class, sid);
		return menuright;
	}
	
	
	public MenuRight findBymenuid(IMyDb db,String menuid,String rightid) throws Exception{
		String queryString = "SELECT * FROM tb_sus_menuright WHERE MENUID=? AND RIGHTID=?";
		MenuRight menu = (MenuRight) dbFactory.getOne(db, queryString,MenuRight.class, menuid,rightid);
		return menu;
	}
	
	public void del(IMyDb db,String menuid,String rightids) throws Exception{
		String querystring = "DELETE FROM tb_sus_menuright WHERE MENUID=?";
		if(StringUtils.isNotBlank(rightids)){
			querystring = querystring + " AND RIGHTID not in ("+rightids+")";
		}
		dbFactory.execute(db, querystring, menuid);
	}

	/**
	 * 
	 * @param conn
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public List<Navmenu> getuser(IMyDb db,String userid) throws Exception{
		StringBuffer SQL = new StringBuffer("select * from tb_sus_navmenu WHERE menuid in (select a.MENUID from tb_sus_menuright a ");
		SQL.append("LEFT JOIN tb_sus_userroleright b on a.RIGHTID=b.RIGHTID ");
		SQL.append("WHERE b.USERID=? group by a.MENUID)");
		List<Navmenu> navmenus =  dbFactory.query(db, SQL.toString(), Navmenu.class,userid);
		return navmenus;
	}
	
//	/**
//	 * 
//	 * @param conn
//	 * @param parentmenuidstr
//	 * @return
//	 * @throws Exception
//	 */
//	private List<Navmenu> getuser2(IMyDb db,String parentmenuidstr) throws Exception{
//		String queryString = "select * from tb_sus_navmenu WHERE menuid in ("+parentmenuidstr+")";
//		List<Navmenu> navmenus =  dbFactory.query(db, queryString, Navmenu.class);
//		return navmenus;
//	}
	
	public JSONArray getMenu(IMyDb db,String userid) throws Exception{
//		List<Navmenu> navmenus = getuser(db, userid);
//		int j=0;
//		String v = "";
//		j=navmenus.size();
//		while(j>0){
//			String vp="";
//			for (Navmenu navmenu : navmenus) {
//				if(StringUtils.isBlank(v)){
//					v= v+navmenu.getMenuid();
//				}else{
//					v= v +","+ navmenu.getMenuid();
//				}
//				if(StringUtils.isBlank(vp)){
//					if(navmenu.getParentmenuid()!=null)
//					vp = vp + navmenu.getParentmenuid();
//				}else{
//					if(navmenu.getParentmenuid()!=null)
//					vp = vp +","+ navmenu.getParentmenuid();
//				}
//			}
//			if(StringUtils.isBlank(vp)){
//				j=0;
//			}else{
//				navmenus = getuser2(db,vp);
//				j=navmenus.size();
//			}
//		}
//		if(StringUtils.isBlank(v)) return new JSONArray();
//		return new JSONArray(navmenuManager.getusertree(db, "1", v));
		
		
		List<Navmenu> navmenus = navmenuManager.findAll(db);
		
		List<Navmenu> menus = getuser(db, userid);
		Map<String, Object> maps = new HashMap<String, Object>();
		for (Navmenu navmenu : menus) {
			maps.put(navmenu.getMenuid(), navmenu);
			if(!"1".equalsIgnoreCase(navmenu.getParentmenuid())){
				maps = getParent(navmenus, maps, navmenu.getParentmenuid());
				maps = getchildren(navmenus, maps, navmenu.getMenuid());
			}
		}
//		for (Navmenu navmenu : navmenus) {
//			System.out.println(navmenu.getMenuid()+"|"+navmenu.getMenuname()+"|"+navmenu.getNindex());
//			
//		}
		
		return JSON.parseArray(JSON.toJSONString(getusertree(navmenus, maps, "1")));
	}
	
	private static Map<String,Object> getParent(List<Navmenu> navmenus,Map<String, Object> maps,String menuid){
		for (Navmenu navmenu : navmenus) {
			if(StringUtils.equalsIgnoreCase(navmenu.getMenuid(), menuid)){
				maps.put(navmenu.getMenuid(), navmenu);
				if(!"1".equalsIgnoreCase(navmenu.getParentmenuid())){
					maps = getParent(navmenus, maps, navmenu.getParentmenuid());
				}
			}
		}
		return maps;
	}
	
	private static Map<String,Object> getchildren(List<Navmenu> navmenus,Map<String, Object> maps,String menuid){
		for (Navmenu navmenu : navmenus) {
			if(StringUtils.equalsIgnoreCase(navmenu.getParentmenuid(), menuid)){
				maps.put(navmenu.getMenuid(), navmenu);
				maps = getchildren(navmenus, maps, navmenu.getMenuid());
			}
		}
		return maps;
	}
	
	
	public static List<JSONObject> getusertree(List<Navmenu> navmenus,Map<String, Object> maps,String pid) throws Exception{
		List<JSONObject> lists = new ArrayList<JSONObject>();
		for (Navmenu navmenu : navmenus) {
			if(StringUtils.equalsIgnoreCase(navmenu.getParentmenuid(), pid)&&maps.get(navmenu.getMenuid())!=null){
				JSONObject orgObject = new JSONObject();
				orgObject.put("id", navmenu.getMenuid());
				orgObject.put("text",navmenu.getMenuname());
				orgObject.put("value",navmenu.getSlink());
				orgObject.put("isexpand", navmenu.getParentmenuid() == null?true:false);
				orgObject.put("checkstate", 0);
				List<JSONObject> list2 = getusertree(navmenus,maps,navmenu.getMenuid());
				if (list2.size() > 0) {
					orgObject.put("hasChildren", true);
					orgObject.put("showcheck", false);
				} else {
					orgObject.put("hasChildren", false);
					orgObject.put("showcheck", true);
				}
				orgObject.put("ChildNodes",list2);
				orgObject.put("complete", true);
				orgObject.put("pid", navmenu.getParentmenuid());
				lists.add(orgObject);
			}
		}
		return lists;
	}
}
